<template>
  <view class="box-bg">
    <uni-nav-bar shadow left-icon="left" right-icon="search" height="65px" leftText="返回" title="选择城市"
      @clickRight="search" @clickLeft="back" style="position: relative; overflow: hidden;"></uni-nav-bar>
    <!-- 搜索框作为导航栏子元素 -->
    <view class="search-bar" v-show="isSearching"
      :style="{ position: 'absolute', right: '0', top: '0', bottom: '0', width: isSearching ? '80%' : '0', transition: 'width 0.3s' }">
      <input type="text" placeholder="输入城市名称搜索" v-model="searchKeyword" @confirm="handleSearch"
        style="width: calc(100% - 40rpx); height: 50%; padding-right: 40rpx;position: relative;top:28rpx" />
      <!-- 取消按钮调整：改为叉号（×），位于搜索框内右侧 -->
      <button @click="cancelSearch" style="
            position: absolute; 
            right: 0rpx; 
            top: 55rpx; 
            transform: translateY(-50%);
            font-size: 32rpx;
            color: #666;
            border-radius: 50%;
            background-color: white;
            border: none;
            color: #1786FF;
          ">
        ×
      </button>
    </view>
    <view class="search-result" v-show="searchKeyword && filteredList.length > 0"
      style="position: absolute; top: 65px; left: 0; right: 0; background: white; border-bottom: 1rpx solid #eee; z-index: 999;">
      <uni-list>
        <!-- 直接使用城市名称字符串（无需 .name） -->
        <uni-list-item v-for="(city, index) in filteredList" :key="index" :title="city" @click="handleSearchResultClick(city)" />
      </uni-list>
    </view>
  </view>
  <view class="main">
    <view class="dingwei-city">定位城市</view>
    <view class="dingwei-city-but">
      <!-- 添加 key 强制重新渲染 -->
      <button :key="currentCity">{{ currentCity }}</button>
      <button style="background-color: #F5F5F5;border:none;color:#1786FF" @click="reLocate">重新定位</button>
    </view>
    <view class="remen-city">热门城市</view>
    <view class="remen-city-but">
      <button @click="handleHotCityClick('上海')">上海</button>
      <button @click="handleHotCityClick('深圳')">深圳</button>
      <button @click="handleHotCityClick('广州')">广州</button>
    </view>
    <view class="remen-city-but">
      <button @click="handleHotCityClick('成都')">成都</button>
      <button @click="handleHotCityClick('三亚')">三亚</button>
      <button @click="handleHotCityClick('杭州')">杭州</button>
    </view>
    <view class="remen-city-but">
      <button @click="handleHotCityClick('西安')">西安</button>
      <button @click="handleHotCityClick('南京')">南京</button>
      <button @click="handleHotCityClick('厦门')">厦门</button>
    </view>
    <view class="uni-padding-wrap uni-common-mt">
      <uni-segmented-control :current="current" :values="items" style-type="text" active-color="#007aff"
        @clickItem="onClickItem" />
    </view>
    <view class="content">
      <view class="content-city" v-if="current === 0">
        <uni-indexed-list class="content-city-list" :options="list1" :show-select="true" @click="bindClick1" />
      </view>
      <view class="content-city" v-if="current === 1">
        <uni-indexed-list class="content-city-list" :options="list2" :show-select="true" @click="bindClick2" />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue'
import cities from '@/common/cities.js'
import wordcities from '@/common/WordCities.js'
import unirequest from '@/untils/unirequest'

// 响应式数据
const current = ref(0)
const items = ref(['国内', '国外'])
const list1 = ref(cities.list)
const list2 = ref(wordcities.list)
const currentCity = ref('焦作')
const isSearching = ref(false) // 控制搜索框是否显示
const searchKeyword = ref('') // 搜索关键字
const filteredList = ref([])
// 方法
const reLocate = async () => {
  try {
    const locationRes = await new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'wgs84',
        success: resolve,
        fail: reject
      });
    });
    const { latitude, longitude } = locationRes;
    console.log('获取到经纬度:', { latitude, longitude });

    // 调用Spring Boot代理接口（假设baseUrl是你的后端地址，如http://localhost:8080）
    const res = await unirequest({
      url: `http://localhost:9301/api/geocoder?latitude=${latitude}&longitude=${longitude}`,  // 后端代理接口路径
      method: 'GET'
    });
    console.log('后端接口响应:', res.data);
    const responseStatus = res.data.status ?? res.data.code ?? -1;
    if (responseStatus === 0) {
      // 根据实际返回结构调整 city 字段路径（示例为 res.data.result.city）
      const city = res.data.result?.address_component?.city || res.data.result?.city;
      if (city) {
        currentCity.value = city;
        uni.showToast({ title: `定位到${city}`, icon: 'success' });
        uni.$emit('citySelected', city);
        // 新增：返回上一页并传递数据
        uni.navigateBack({
          success: () => {
            uni.$emit('citySelected', city); // 传递选中城市到首页
          }
        });
      } else {
        uni.showToast({ title: '后端未返回城市信息', icon: 'none' });
      }
    } else {
      const errorMsg = res.data.msg || '后端接口返回异常';
      uni.showToast({ title: `获取城市失败: ${errorMsg}`, icon: 'none' });
    }
  } catch (error) {
    // 处理权限拒绝的情况
    if (error.errMsg.includes('auth deny')) {
      uni.showModal({
        title: '权限申请',
        content: '需要位置权限以获取当前城市，请授权',
        success: (res) => {
          if (res.confirm) {
            uni.openSetting({
              success: (settingRes) => {
                if (settingRes.authSetting['scope.userLocation']) {
                  reLocate(); // 授权后重新定位
                }
              }
            });
          }
        }
      });
    } else {
      // 新增：显示具体错误信息
      const errorMsg = error.errMsg || '未知错误';
      uni.showToast({
        title: `定位失败: ${errorMsg}`,
        icon: 'none',
        duration: 3000 // 延长提示时间，确保用户看到
      });
      console.error('定位失败:', error);
    }
  }
}
const bindClick1 = (e) => {
  const selectedCity = e.item?.name || e.item?.label || '未知城市';
  currentCity.value = selectedCity; // 更新当前城市
  uni.showToast({ title: `已选择${selectedCity}`, icon: 'success' });
  // 修改：在返回成功后触发全局事件
  uni.navigateBack({
    success: () => {
      uni.$emit('citySelected', selectedCity); // 传递选中城市到首页
    }
  });
}

const bindClick2 = (e) => {
  const selectedCity = e.item?.name || e.item?.label || '未知城市';
  currentCity.value = selectedCity; // 更新当前城市
  uni.showToast({ title: `已选择${selectedCity}`, icon: 'success' });
  // 修改：在返回成功后触发全局事件
  uni.navigateBack({
    success: () => {
      uni.$emit('citySelected', selectedCity); // 传递选中城市到首页
    }
  });
}
const handleHotCityClick = (city) => {
  currentCity.value = city; // 更新当前城市
  uni.showToast({ title: `已选择${city}`, icon: 'success' });
  // 修改：在返回成功后触发全局事件
  uni.navigateBack({
    success: () => {
      uni.$emit('citySelected', city); // 传递选中城市到首页
    }
  });
};
const handleSearchResultClick = (city) => {
  console.log('触发搜索结果点击事件，选中城市:', city); 
  currentCity.value = city; // 更新当前城市
  console.log('currentCity 更新后:', currentCity.value);

  isSearching.value = false;
  searchKeyword.value = '';
  // 新增：返回上一页并传递数据
  uni.navigateBack({
    success: () => {
      uni.$emit('citySelected', city); // 传递选中城市到首页
    }
  });
};

const search = () => {
  isSearching.value = true
  // 可选：自动聚焦输入框
  setTimeout(() => {
    const input = document.querySelector('.search-bar input')
    input && input.focus()
  }, 100)
}
// 监听关键字变化，实时过滤城市
watch(searchKeyword, (newVal) => {
  // 合并国内和国外城市数据（提取所有字符串类型的城市名称）
  const allCities = [
    ...cities.list.flatMap(group => group.data),  // group.data 是字符串数组（如 ["阿克苏", "北京"]）
    ...wordcities.list.flatMap(group => group.data)  // 假设 WordCities.js 结构相同
  ];

  // 直接使用字符串的 includes 方法过滤（关键修复）
  filteredList.value = allCities.filter(city =>
    city.includes(newVal)  // city 是字符串，直接检查是否包含关键字
  );
  console.log('搜索关键字:', newVal, '过滤结果:', filteredList.value);  // 验证过滤结果是否正确
})
// 取消搜索
const cancelSearch = () => {
  isSearching.value = false // 隐藏搜索框
  searchKeyword.value = '' // 清空关键字
  // 恢复原始城市列表显示
  if (current.value === 0) {
    list1.value = cities.list // 假设原始列表未被修改过
  } else {
    list2.value = wordcities.list
  }
}
// 处理搜索（可根据需求改为实时搜索或确认后搜索）
const handleSearch = () => {
  if (current.value === 0) {
    list1.value = filteredList.value // 更新国内城市列表为过滤结果
  } else {
    list2.value = filteredList.value // 更新国外城市列表为过滤结果
  }
}
const onClickItem = (e) => {
  current.value = e.currentIndex; // 关键修改：直接通过 e.currentIndex 获取标签索引
  console.log('当前标签索引:', current.value); // 预期输出 0（国内）或 1（国外）
  console.log('当前国外列表数据:', list2.value); 
};

const back = () => {
  uni.navigateBack();
};
</script>

<style>
.main {
  padding: 25rpx;
}

.uni-padding-wrap {
  width: 100%;
  border-bottom: 2rpx solid #BCBCBC
}

.content {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  justify-content: center;
  align-items: center;
  height: 150px;
  text-align: center;
}

.dingwei-city,
.remen-city {
  color: #AEAEAE;
}

.content-city-list {
  height: 920rpx;
  margin-top: 680rpx;
}

.dingwei-city-but,
.remen-city-but {
  display: flex;
  margin-top: 10rpx;
  margin-bottom: 10rpx;
}

.dingwei-city-but button {
  width: 49%;
  background-color: #EBF2FA;
  border: 1rpx solid #CDE1F6;
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏溢出 */
  text-overflow: ellipsis;
  /* 溢出显示省略号（可选，若需完整显示可移除） */
}

.remen-city-but button {
  width: 32%;
  background-color: #EBF2FA;
  border: 1rpx solid #CDE1F6
}

/* 调整搜索框样式 */
.search-bar {
  background: white;
  border-left: 1rpx solid #eee;
  height: 110rpx;
  border: none;
}

.search-bar input {
  background: transparent;
  border-radius: 0;
  font-size: 28rpx;
  padding: 0 20rpx;
  background-color: white;
}

.search-result {
  max-height: 300rpx;
  /* 最大高度限制 */
  overflow-y: auto;
  /* 超出内容滚动 */
}

.search-result uni-list-item {
  font-size: 28rpx;
  padding: 0 25rpx;
  /* 与.main区域内边距一致 */
}
</style>